package com.explorx.sns.puma.im.core.controller;

import com.explorex.puma.common.login.LoginUser;
import com.explorex.puma.common.login.TokenService;
import com.explorex.puma.common.login.User;
import com.explorex.puma.common.web.HttpResult;
import com.explorx.sns.puma.im.core.chat.UserInfoDomainService;
import com.explorx.sns.puma.im.core.chat.consts.Constants;
import com.explorx.sns.puma.im.core.chat.model.RegisterModel;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@Slf4j
@RestController
@RequestMapping("/api/user")
public class UserRegisterController {

    @Value("${token.header:Authorization}")
    private String header;


    @Resource
    private UserInfoDomainService userInfoDomainService;

    @Resource
    private TokenService tokenService;

    @PostMapping("/v1/register")
    public HttpResult register(@RequestBody RegisterModel req,HttpServletResponse httpServletResponse){
        boolean register=false;
        try {
            Preconditions.checkArgument(StringUtils.isNoneBlank(req.getPassword()));
            Preconditions.checkArgument(StringUtils.isNoneBlank(req.getUsername()));
            Preconditions.checkArgument(StringUtils.isNoneBlank(req.getPassword()));
            final Long userId = userInfoDomainService.register(req);
            if(userId>0){
                register=true;
                addCookies(userId,req.getUsername(),httpServletResponse);
            }
        }catch (IllegalArgumentException e){
            return  HttpResult.fail(-1,e.getMessage());
        }catch (Exception e){
            return  HttpResult.fail(-1,"失败");
        }
        return  register ?  HttpResult.success() : HttpResult.fail(-1,"失败");
    }

    private void addCookies(Long userId,String userName, HttpServletResponse httpServletResponse){
        LoginUser currentUsr=LoginUser.builder()
                .user(new User(userId,userName,System.currentTimeMillis())).userName(userName).build();
        final String token = tokenService.createToken(currentUsr);
        httpServletResponse.addHeader(header,token);
        Cookie tokenCookie=new Cookie("token", Constants.TOKEN_PREFIX+token);
        tokenCookie.setPath("/api");
        httpServletResponse.addCookie(tokenCookie);
    }
}
